package com.hengxinguotong.zhihuichengjian.ui;

import android.app.AlertDialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.Video;
import com.hengxinguotong.zhihuichengjian.bean.VideoRes;
import com.hikvision.sdk.consts.SDKConstant.LiveSDKConstant;
import com.hengxinguotong.zhihuichengjian.video.CustomSurfaceView;
import com.hengxinguotong.zhihuichengjian.video.UIUtils;
import com.hikvision.sdk.VMSNetSDK;
import com.hikvision.sdk.consts.SDKConstant;
import com.hikvision.sdk.net.bean.CustomRect;
import com.hikvision.sdk.net.bean.SubResourceNodeBean;
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness;
import com.hikvision.sdk.utils.FileUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/5/29
 */

public class PlatformVideoActivity extends BaseActivity implements View.OnClickListener, SurfaceHolder.Callback, View.OnTouchListener {
    /**
     * 获取监控点信息成功
     */
    private static final int GET_CAMERA_INFO_SUCCESS = 1;
    /**
     * 获取监控点信息失败
     */
    private static final int GET_CAMERA_INFO_FAILURE = 2;
    /**
     * 预览控件
     */
    private CustomSurfaceView mSurfaceView = null;
    /**
     * 云台控制菜单
     */
    @BindView(R.id.rl_orientation)
    RelativeLayout rlOrientation;
    /**
     * 顶部菜单
     */
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    /**
     * 底部菜单
     */
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    /**
     * 高清标清切换按钮
     */
    @BindView(R.id.tv_video_quality)
    TextView tvVideoQuality;
    /**
     * 视频名称标签
     */
    @BindView(R.id.tv_video_name)
    TextView tvVideoName;
    /**
     * 背景
     */
    @BindView(R.id.ll_beijing)
    LinearLayout llBeijing;
    /**
     * 刷新按钮
     */
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    /**
     * 标题标签
     */
    @BindView(R.id.tv_project_name)
    TextView tvProjectName;
    /**
     * 是否开始或停止云台控制
     */
    private String mIsPtzStart;
    /**
     * 云台控制命令
     */
    private int mPtzCommand;
    /**
     * 码流类型
     */
    private int mStreamType = LiveSDKConstant.MAIN_HIGH_STREAM;
    /**
     * 监控点资源
     */
    private SubResourceNodeBean mCamera = null;
    /**
     * 视图更新处理Handler
     */
    private Handler mHandler = null;
    /**
     * 对讲通道数目
     */
    private int talkChannels;
    /**
     * 临时选择对讲通道数目
     */
    private String channelNoTemp;
    /**
     * 最终选择对讲通道数目
     */
    private int channelNo;

    /**
     * 播放窗口1
     */
    private int PLAY_WINDOW_ONE = 1;
    /**
     * sdk实例
     */
    private VMSNetSDK mVMSNetSDK = null;

    /**
     * 视图更新处理器
     */
    private class MyHandler extends Handler {

        WeakReference<PlatformVideoActivity> mActivityReference;

        MyHandler(PlatformVideoActivity activity) {
            mActivityReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PlatformVideoActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case GET_CAMERA_INFO_SUCCESS:
                        UIUtils.cancelProgressDialog();
                        UIUtils.showToast(activity, R.string.rtsp_success);
                        //开启定时
                        startTiming();
                        llBeijing.setVisibility(View.GONE);
                        break;
                    case GET_CAMERA_INFO_FAILURE:
                        UIUtils.cancelProgressDialog();
                        UIUtils.showToast(activity, R.string.rtsp_fail);
                        llBeijing.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private VideoRes videoRes;
    private int index;//摄像头的下标
    private List<SubResourceNodeBean> list;//摄像头的集合

    private int startTime;
    private int endTime;
    private Date date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        ButterKnife.bind(this);
        initMeasure();
        initData();
        initView();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mHandler = new MyHandler(this);
        videoRes = (VideoRes) getIntent().getSerializableExtra("videoRes");
        index = getIntent().getIntExtra("position", 0);

        list = new ArrayList<SubResourceNodeBean>();
        for (int i = 0; i < videoRes.getValue().getCameraList().size(); i++) {
            Video video = videoRes.getValue().getCameraList().get(i);
            SubResourceNodeBean camera = new SubResourceNodeBean();
            camera.setName(video.getName());
            camera.setIsOnline(video.getIsOnline());
            camera.setSysCode(video.getSysCode());
//            camera.setId(video.getId());
            camera.setNodeType(video.getNodeType());
            camera.setState(video.getFlag());//这个设置其实不准，state不是flag，不过没有位置放flag，就暂时这样使用，暂时不影响视频
            list.add(camera);
        }

        mCamera = list.get(index);
        mVMSNetSDK = VMSNetSDK.getInstance();
        date = new Date(System.currentTimeMillis());
        startTime = (int) (date.getTime() / 1000);
        tvProjectName.setText(mCamera.getName());
    }

    /**
     * 初始化视图
     */
    private void initView() {
        mSurfaceView = (CustomSurfaceView) findViewById(R.id.surfaceView);
        mSurfaceView.getHolder().addCallback(this);
        mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                date = new Date(System.currentTimeMillis());
                startTime = (int) (date.getTime() / 1000);
                startTiming();
                return false;
            }
        });

        //开始播放
        clickStartBtn();
    }

    /**
     * 开始视频
     */
    private void clickStartBtn() {
        if (null == mCamera) {
            mHandler.sendEmptyMessage(GET_CAMERA_INFO_FAILURE);
            return;
        }
        UIUtils.showLoadingProgressDialog(this, R.string.loading_process_tip);
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                mVMSNetSDK.startLiveOpt(PLAY_WINDOW_ONE, mCamera.getSysCode(), mSurfaceView, mStreamType, new OnVMSNetSDKBusiness() {
                    @Override
                    public void onFailure() {
                        mHandler.sendEmptyMessage(GET_CAMERA_INFO_FAILURE);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        mHandler.sendEmptyMessage(GET_CAMERA_INFO_SUCCESS);
                    }
                });
                Looper.loop();
            }
        }.start();
    }

    /**
     * 停止视频
     */
    private void clickStopBtn() {
        //停止预览按钮点击操作
        boolean stopLiveResult = mVMSNetSDK.stopLiveOpt(1);
        if (stopLiveResult) {
            UIUtils.showToast(this, R.string.live_stop_success);
        }
    }

    /**
     * 抓拍
     */
    private void clickCaptureBtn() {
        //抓拍按钮点击操作
        int opt = mVMSNetSDK.captureLiveOpt(PLAY_WINDOW_ONE, FileUtils.getPictureDirPath().getAbsolutePath(), "Picture" + System.currentTimeMillis() + ".jpg");
        switch (opt) {
            case SDKConstant.LiveSDKConstant.SD_CARD_UN_USABLE:
                UIUtils.showToast(this, R.string.sd_card_fail);
                break;
            case SDKConstant.LiveSDKConstant.SD_CARD_SIZE_NOT_ENOUGH:
                UIUtils.showToast(this, R.string.sd_card_not_enough);
                break;
            case SDKConstant.LiveSDKConstant.CAPTURE_FAILED:
                UIUtils.showToast(this, R.string.capture_fail);
                break;
            case SDKConstant.LiveSDKConstant.CAPTURE_SUCCESS:
                UIUtils.showToast(this, R.string.capture_success);
                break;
        }
    }

    private void startTiming() {
        if(rlBottom.isShown() || rlTop.isShown()){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Date date = new Date(System.currentTimeMillis());
                    endTime = (int) (date.getTime() / 1000);
                    if (endTime - startTime > 5) {
                        startAnimation();
                    }
                }
            }, 6000);
        }else{
            //权宜之计
            if(mCamera.getState() == 1){
                rlOrientation.setVisibility(View.VISIBLE);
            }else{
                rlOrientation.setVisibility(View.GONE);
            }
            rlTop.setVisibility(View.VISIBLE);
            rlBottom.setVisibility(View.VISIBLE);
            startTiming();
            System.gc();
        }
    }

    /***
     *  云台控制菜单显示按钮点击事件
     *  是否显示云台控制菜单
     */
    private void startAnimation() {
        if (pw != null) {
            pw.dismiss();
        }
        rlOrientation.setVisibility(View.GONE);
        rlTop.setVisibility(View.GONE);
        rlBottom.setVisibility(View.GONE);
    }

    @OnTouch({R.id.iv_up, R.id.iv_down, R.id.iv_left, R.id.iv_right, R.id.iv_camera_add, R.id.iv_camera_reduce})
    public boolean onTouch(View view, MotionEvent motionEvent) {
        date = new Date(System.currentTimeMillis());
        startTime = (int) (date.getTime() / 1000);
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            //开始云台控制
            mIsPtzStart = SDKConstant.PTZCommandConstant.ACTION_START;
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            //停止云台控制
            mIsPtzStart = SDKConstant.PTZCommandConstant.ACTION_STOP;
            //开始计时
            startTiming();
        }
        switch (view.getId()){
            case R.id.iv_up:
                //云台向上命令
                mPtzCommand = SDKConstant.PTZCommandConstant.CUSTOM_CMD_UP;
                break;
            case R.id.iv_down:
                //云台向下命令
                mPtzCommand = SDKConstant.PTZCommandConstant.CUSTOM_CMD_DOWN;
                break;
            case R.id.iv_left:
                //云台向左命令
                mPtzCommand = SDKConstant.PTZCommandConstant.CUSTOM_CMD_LEFT;
                break;
            case R.id.iv_right:
                //云台向右命令
                mPtzCommand = SDKConstant.PTZCommandConstant.CUSTOM_CMD_RIGHT;
                break;
            case R.id.iv_camera_add:
                //云台放大命令
                mPtzCommand = SDKConstant.PTZCommandConstant.CUSTOM_CMD_ZOOM_IN;
                break;
            case R.id.iv_camera_reduce:
                //云台缩小命令
                mPtzCommand = SDKConstant.PTZCommandConstant.CUSTOM_CMD_ZOOM_OUT;
                break;
        }
        //云台控制按钮点击方法
        ptzBtnOnClick();
        return true;
    }

    @OnClick({R.id.iv_back, R.id.iv_refresh, R.id.iv_camera_left, R.id.iv_camera_right, R.id.iv_camera_camera, R.id.tv_video_quality})
    public void onClick(View v) {
        date = new Date(System.currentTimeMillis());
        startTime = (int) (date.getTime() / 1000);
        switch (v.getId()) {
            case R.id.iv_refresh:
                //开始预览按钮点击操作
                clickStartBtn();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_camera_camera:
                //抓拍按钮点击操作
                clickCaptureBtn();
                break;
            case R.id.iv_camera_left:
                //上一个按钮点击操作
                clickStopBtn();
                if (index == 0) {
                    index = list.size() - 1;
                } else {
                    index = index - 1;

                }
                mCamera = list.get(index);
                tvProjectName.setText(mCamera.getName());
                clickStartBtn();
                break;
            case R.id.iv_camera_right:
                //下一个按钮点击操作
                clickStopBtn();
                if (index == list.size() - 1) {
                    index = 0;
                } else {
                    index = index + 1;

                }
                mCamera = list.get(index);
                tvProjectName.setText(mCamera.getName());
                clickStartBtn();
                break;
            case R.id.tv_video_quality:
                showPopupWindow(v);
                break;
            case R.id.tv_high:
                //高清
                clickStopBtn();
                mStreamType = LiveSDKConstant.MAIN_HIGH_STREAM;
                pw.dismiss();
                tvVideoQuality.setText("高清");
                clickStartBtn();
                break;
            case R.id.tv_sub:
                //标清
                clickStopBtn();
                mStreamType = LiveSDKConstant.SUB_STREAM;
                pw.dismiss();
                tvVideoQuality.setText("标清");
                clickStartBtn();
                break;
            case R.id.tv_standard:
                //流畅
                clickStopBtn();
                mStreamType = LiveSDKConstant.SUB_STANDARD_STREAM;
                pw.dismiss();
                tvVideoQuality.setText("流畅");
                clickStartBtn();
                break;
            default:
                break;
        }
        startTiming();
    }

    private PopupWindow pw;
    private int width;// 屏幕的宽度
    private int height;// 屏幕的高度

    //弹出一个PopupWindow的窗体
    private void showPopupWindow(View view) {
        float w = (float) (width / 6.3);
        View v = LayoutInflater.from(this).inflate(R.layout.video_popup_window, null);
        TextView tv_high = (TextView) v.findViewById(R.id.tv_high);
        tv_high.setOnClickListener(this);
        TextView tv_sub = (TextView) v.findViewById(R.id.tv_sub);
        tv_sub.setOnClickListener(this);
        TextView tv_standard = (TextView) v.findViewById(R.id.tv_standard);
        tv_standard.setOnClickListener(this);
        pw = new PopupWindow(v, view.getWidth() - 10, (int) w);
        pw.setFocusable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        pw.showAsDropDown(view, 5, 10);

    }

    private void initMeasure() {
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels;
    }

    /***
     * 云台控制按钮点击
     */
    private void ptzBtnOnClick() {
        //云台操作
        VMSNetSDK.getInstance().sendPTZCtrlCommand(PLAY_WINDOW_ONE, true, mIsPtzStart, mPtzCommand, 256, new OnVMSNetSDKBusiness() {//第一个参数为播放窗口参数，第二个参数为是否为非预置点命令，第三个参数为开始或停止，第四个参数为云台控制命令，第五个参数为预置点值，最大255，第六个参数为回调接口
            @Override
            public void onFailure() {
                Toast.makeText(PlatformVideoActivity.this, R.string.ptz_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(Object obj) {
                Toast.makeText(PlatformVideoActivity.this, R.string.ptz_success, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        //页面销毁时停止预览
        boolean stopLiveResult = VMSNetSDK.getInstance().stopLiveOpt(1);
        if (stopLiveResult) {
            UIUtils.showToast(this, R.string.live_stop_success);
        }
    }

}
